package com.mojo.concurrent.concurrent_02_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock锁使用示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/17 11:22
 */
public class Lock1 {
    private static Integer n = 0;
    //默认非公平锁
    final static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {


        Thread t1 = new Thread(() -> {
            increase();
        });
        Thread t2 = new Thread(() -> {
            increase();
        });
        t1.start();
        t2.start();
        t2.join();
        t1.join();
        System.out.println(">>>>>>" + n);
    }

    private static void increase() {
        for (int i = 0; i < 50; i++) {
            lock.lock();
            try {
                n++;
                System.out.println(Thread.currentThread().getName() + ">>" + n);
            } finally {
                lock.unlock();
            }
        }
    }
}
